package com.sdry.service.impl.llm;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.sdry.mapper.llm.DepartmentMapper;
import com.sdry.mapper.llm.EmployeeMapper;
import com.sdry.mapper.llm.EmployeeRecordMapper;
import com.sdry.mapper.llm.RoleMapper;
import com.sdry.mapper.llm.TeamMapper;
import com.sdry.mapper.llm.UserMapper;
import com.sdry.model.llm.Department;
import com.sdry.model.llm.Employee;
import com.sdry.model.llm.EmployeeRecord;
import com.sdry.model.llm.Permission;
import com.sdry.model.llm.Role;
import com.sdry.model.llm.RoleBean;
import com.sdry.model.llm.Team;
import com.sdry.model.llm.User;
import com.sdry.model.llm.UserRole;
import com.sdry.service.llm.UserService;
import com.sdry.utils.MD5;
import com.sdry.utils.RoleUtils;

/**
 * @author lian
 * @version 1.0
 * @time 2018年10月17日 上午12:57:25
 */

@Service
public class UserServiceImp implements UserService {

	@Resource
	private UserMapper userMapper; // 注入用户mapper
	@Resource
	private RoleMapper roleMapper; // 注入角色mapper
	@Resource
	private TeamMapper teamMapper; // 注入班组mapper
	@Resource
	private EmployeeMapper employeeMapper; // 注入员工管理mapper
	@Resource
	private EmployeeRecordMapper employeeRecordMapper; // 注入员工记录mapper
	@Resource
	private DepartmentMapper depMapper; // 注入部门mapper

	/**
	 * 查询用户总行数
	 * @param user 用户
	 * @return
	 */
	@Override
	public int countUser(User user) {
		return userMapper.countUser(user);
	}

	/**
	 * 分页查询用户
	 * @param map 参数集合
	 * @return
	 */
	@Override
	public List<User> listPageUser(Map<String, Object> map) {
		List<User> list = userMapper.listPageUser(map);
		for(User user : list){
			if(null != user.getDepName() && !"".equals(user.getDepName())){
				Department dep = depMapper.getDepartmentByDid(Long.parseLong(user.getDepName()));
				if(null != dep){
					user.setDepName(dep.getName());
				}
			}
		}
		return list;
	}

	/**
	 * 新增用户
	 * @param user 用户
	 * @return
	 */
	@Override
	public int insertUser(User user) {
		int isSuccess = -2;
		List<User> list = userMapper.getUserByAccount2(user.getAccount());
		if(list.size() == 0){
			user.setPassword(MD5.md5Encode("123"));
			user.setStatus("在职");
			if(null != user.getDepName() && !"".equals(user.getDepName())){
				Department dep = depMapper.getDepartmentByDname(user.getDepName());
				if(null != dep){
					user.setDepName(dep.getDid().toString());
				}
			}
			int i = userMapper.insertUser(user);
			if(i > 0){
				isSuccess = 2;
			}
		}
		return isSuccess;
	}

	/**
	 * 修改用户
	 * @param user 用户
	 * @return
	 */
	@Override
	public int updateUser(User user) {
		int isSuccess = -3;
		//如果有离职日期
		if(null != user.getTname() && !"".equals(user.getTname())){
			user.setStatus("离职");
		}
		if(null != user.getDepName() && !"".equals(user.getDepName())){
			Department dep = depMapper.getDepartmentByDname(user.getDepName());
			if(null != dep){
				user.setDepName(dep.getDid().toString());
			}
		}
		//设定初始密码
		if(user.getRemark3() != null && !"".equals(user.getRemark3())){
			String encode = MD5.md5Encode(user.getRemark3());
			user.setPassword(encode);
		}
		User u = userMapper.findUserByUid(user.getUid());
		if(u.getAccount().equals(user.getAccount())){
			int i = userMapper.updateUser(user);
			if(i > 0){
				isSuccess = 3;
			}
		}else{
			List<User> list = userMapper.getUserByAccount2(user.getAccount());
			if(list.size() == 0){
				int i = userMapper.updateUser(user);
				if(i > 0){
					isSuccess = 3;
				}
			}
		}
		return isSuccess;
	}

	/**
	 * 删除用户
	 * @param uid 用户ID
	 * @return
	 */
	@Transactional(rollbackFor = { Exception.class })
	public int deleteUser(String str) {
		int isSuccess = 0;
		String[] split = str.split(",");
		try {
			for (String uid : split) {
				isSuccess = userMapper.deleteUser(Long.parseLong(uid));
				if(isSuccess > 0){
					userMapper.deleteUserInUserRole(Long.parseLong(uid));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}
		return isSuccess;
	}

	/**
	 * 用户登陆
	 * @param user  用户
	 * @return
	 */
	@Override
	public User login(User user) {
		return userMapper.login(user);
	}

	/**
	 * 给用户授予角色
	 * @param rids 角色ID组成的字符串
	 * @return
	 */
	@Transactional(rollbackFor = { Exception.class })
	public int accreditUser(String rids,  String uid) {
		int isSuccess = 0;
		String[] split = rids.split(",");
		UserRole ur = new UserRole();
		ur.setUid(Long.parseLong(uid));
		try {
			// 在关系表中删除对应的角色数据
			userMapper.deleteUserInUserRole(Long.parseLong(uid));
			// 遍历要授予的角色的ID
			if(rids.length() > 0){
				for (String rid : split) {
					ur.setRid(Long.parseLong(rid));
					// 把数据存到用户和角色关系表中
					isSuccess = userMapper.accreditUser(ur);
				}
			}else{
				isSuccess = 1;
			}
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}
		return isSuccess;
	}

	/**
	 * 获取用户角色
	 * @param uid 用户ID
	 * @return
	 */
	@Override
	public List<RoleBean> getRoleByUser(Long uid) {
		List<Role> allRole = roleMapper.getAllRole();
		List<Role> roleByUserId = roleMapper.getRoleByUserId(uid);
		return RoleUtils.role2bean(allRole, roleByUserId);
	}

	/**
	 * 根据ID获取用户信息
	 * @param uid 用户ID
	 * @return
	 */
	public User findById(Long uid){
		return userMapper.findUserByUid(uid);
	}

	/**
	 * 根据ID获取角色信息
	 * @param uid 用户ID
	 * @return
	 */
	@Override
	public List<Role> getRoleIdByUserId(Long uid) {
		return roleMapper.getRoleByUserId(uid);
	}

	/**
	 * 根据ID获取部门信息
	 * @param uid 用户ID
	 * @return
	 */
	@Override
	public Department getDeparmentByUid(Long uid) {
		return userMapper.getDeparmentByUid(uid);
	}

	/**
	 * 校验是否删除用户
	 * @param str 用户ID组成的字符串
	 * @return
	 */
	@Override
	public int deleteUserOfVerify(String str) {
		int isSuccess = -1;
		String[] split = str.split(",");
		for(int i = 0; i < split.length; i ++){
			Long id = Long.parseLong(split[i]);
			List<Employee> empList = employeeMapper.findEmployeeByUid(id);
			List<EmployeeRecord> erList = employeeRecordMapper.getEmployeeRecordByUid(id);
			List<Team> teamList = teamMapper.getTeamsByUid(id);
			if(empList.size() > 0 || erList.size() > 0 || teamList.size() > 0){
				isSuccess = 1;
				break;
			}
		}
		return isSuccess;
	}

	/**
	 * 根据用户ID获取权限资源信息
	 * @param uid 用户ID
	 * @return
	 */
	@Override
	public List<Permission> getPermissionByUid(Long uid) {
		return userMapper.getPermissionByUid(uid);
	}
}
